package com.eorchis.module.loginauthentication.ui.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.console.common.LoginFilter;
import com.eorchis.core.service.IBaseService;
import com.eorchis.core.springext.mvc.SessionConstant;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.core.ui.controller.AbstractBaseController;
import com.eorchis.module.department.domain.Department;
import com.eorchis.module.department.domain.DepartmentUser;
import com.eorchis.module.loginauthentication.dao.ILoginAuthenticationDao;
import com.eorchis.module.loginauthentication.domain.SysDepSysRoleView;
import com.eorchis.module.loginauthentication.service.ILoginAuthenticationService;
import com.eorchis.module.loginauthentication.ui.commond.LoginAuthenticationQueryCommond;
import com.eorchis.module.loginauthentication.ui.commond.LoginAuthenticationValidCommond;
import com.eorchis.module.security.cas.domain.Role;
import com.eorchis.module.user.domain.User;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * 
 * Title: ConfigurationController<br>
 * Description: <br>
 * Copyright @ 2011~2015 Goldgov .All rights reserved.<br>
 * 
 * @author GuoL
 * @createDate 2015-8-14
 * @version $Revision: $
 */
@Controller("loginAuthenticationController")
@RequestMapping(value = LoginAuthenticationController.MODULE_PATH)
public class LoginAuthenticationController extends AbstractBaseController<LoginAuthenticationValidCommond, LoginAuthenticationQueryCommond> {
	// 模块页面根路径
	public static final String MODULE_PATH = "/module/LoginAuthentication";
	// 登录接口
	@Resource(name = "com.eorchis.module.loginauthentication.service.impl.LoginAuthenticationServiceImpl")
	private ILoginAuthenticationService loginAuthenticationService;
	
	@Resource(name = "com.eorchis.module.loginauthentication.dao.impl.LoginAuthenticationDaoImpl")
	private ILoginAuthenticationDao loginAuthenticationDao;
	
	@Override
	public IBaseService getService() {
		return loginAuthenticationService;
	}

	@Override
	public String getModulePath() {
		return MODULE_PATH;
	}

	/**
	 * 用户登录
	 * @author RongSL 2018年3月28日
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/login")
	public String userLogin(@ModelAttribute("resultList") LoginAuthenticationQueryCommond queryCommond, HttpServletRequest request, HttpServletResponse response, @ModelAttribute("resultState") ResultState resultState) throws Exception {

		HttpSession session = request.getSession();
		String redirectPath = "redirect:/" + LoginFilter.loginPage;
		if (!PropertyUtil.objectNotEmpty(queryCommond.getLoginID()) || !PropertyUtil.objectNotEmpty(queryCommond.getPassword())) {
			session.setAttribute("error", "请输入帐号和密码!");
			return redirectPath;
		}
		try{
			// 判断用户状态 0：不存在 1：密码正确 2：密码错误
			Integer state = loginAuthenticationService.isExistUser(queryCommond);
			if (state.intValue() == 0) {
				session.setAttribute("error", "用户不存在，请重新输入!");
				return redirectPath;
			} else if (state.intValue() == 1) {
				// session.setMaxInactiveInterval(2 * 3600); // Session保存两小时
				List<Role> roles = new ArrayList<Role>();
				Role r;Department d;
				List<Department> scopes;
				Map<String,Role> scopesMap=new HashMap<String,Role>();
				DepartmentUser du=loginAuthenticationDao.findDepartmentUser(queryCommond);
				User user =du.getUser();
				Department department = du.getDepartment();
				
				// 角色和单位集合
				List<SysDepSysRoleView> list=loginAuthenticationDao.findUumSysDepRoleView(queryCommond);
				//角色如果不存在则赋予角色“学员”权限
				if(list.isEmpty()){
					r=loginAuthenticationDao.findRole(queryCommond);
					scopes=new ArrayList<Department>();
					scopes.add(department);
					r.setScopes(scopes);
					roles.add(r);
					scopesMap.put(r.getRoleID(), r);
				}else{
					for(SysDepSysRoleView s:list){
						d=new Department();
						d.setDeptID(s.getDepID().toString());
						d.setDeptName(s.getDepName());
						d.setDeptCode(s.getDepCode());
						d.setTreepath(s.getTreePath());
						d.setParentID(s.getParentID().toString());
						if(PropertyUtil.objectNotEmpty(scopesMap.get(s.getRoleID()))){
							r=scopesMap.get(s.getRoleID());
							r.getScopes().add(d);
						}else{
							r=new Role();
							r.setRoleCode(s.getRoleCode());
							r.setRoleID(s.getRoleID().toString());
							r.setRoleName(s.getRoleName());
							r.setOrderNum(s.getOrderNum());
							scopes=new ArrayList<Department>();
							scopes.add(d);
							r.setScopes(scopes);
							roles.add(r);
							scopesMap.put(r.getRoleID(), r);
						}
					}
				}
				
				// 角色集合
				session.setAttribute(SessionConstant.ROLES, roles);
				if (roles.size() == 1) {
					session.setAttribute(SessionConstant.CURRENT_ROLE, roles.get(0));
				}
				// 用户信息
				session.setAttribute(SessionConstant.USER_INFO, user);
				// 用户部门
				session.setAttribute(SessionConstant.CURRENT_DEPARTMENT, department);
				//登录成功的标识符
				session.setAttribute("loginState", true);
				redirectPath = "redirect:/" + LoginFilter.indexPage;
				return redirectPath;
			} else if (state.intValue() == 2) {
				session.setAttribute("error", "用户密码错误，请重新输入!");
				return redirectPath;
			} else {
				session.setAttribute("error", "系统错误，请联系管理员!");
				return redirectPath;
			}
		}catch(Exception e){
			e.printStackTrace();
			session.setAttribute("error", "系统错误，请联系管理员!");
			return redirectPath;
		}
	}

	/**
	 * 用户退出登录
	 * @author RongSL 2018年3月28日
	 */
	/*@SuppressWarnings("rawtypes")
	@RequestMapping("/logout")
	public String userLogout(@ModelAttribute("resultList") LoginAuthenticationQueryCommond queryCommond, HttpServletRequest request, HttpServletResponse response, @ModelAttribute("resultState") ResultState resultState) throws Exception {
		String forwardPath = "redirect:/" + LoginFilter.loginPage;
		try{
			HttpSession session = request.getSession();
			Enumeration e=session.getAttributeNames();
			while(e.hasMoreElements()){
				session.removeAttribute((String)e.nextElement());
			}
			session.invalidate();
			request.getSession(false);
		}catch(Exception e){
			e.printStackTrace();
		}
		return forwardPath;
	}*/
}
